package cn.gs.serializable.serialize;

// @author gs
import cn.gs.serializable.entity.ArrayEntity;
import cn.gs.serializable.entity.IEntity;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class ArraySerialize extends AGenericSerialize {

    public ArraySerialize() {
    }

    public ArraySerialize(ISerialize ss) {
        super(ss);
    }

    public ArraySerialize(Class<?> cc) {
        super(cc);
    }

    @Override
    public <T> T toObj(cn.gs.serializable.serialize.ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (!(from instanceof ArrayEntity)) {
            return null;
        }
        if (null == clazz) {
            Object o;
            Class[] classes = new Class[]{int[].class, double[].class, String[].class, int[][].class, double[][].class, String[][].class};
            for (Class c : classes) {
                o = toObj(ctrl, from, c);
                if (o != null) {
                    return (T) o;
                }
            }
            return null;
        } else if (!clazz.isArray()) {
            return null;
        } else {
            Class inn = cc == null ? clazz.getComponentType() : cc;
            List<IEntity> entities = ((ArrayEntity) from).getEntities();
            Object array = Array.newInstance(inn, entities.size());
            for (int i = 0; i < entities.size(); ++i) {
                Object o = serialize(ctrl).toObj(ctrl, entities.get(i), inn);
                Array.set(array, i, o);
            }
            return (T) array;
        }
    }

    @Override
    public IEntity fromObj(ISerialize ctrl, Object o) {
        if (o != null && o.getClass().isArray()) {
            int len = Array.getLength(o);
            List<IEntity> entities = new ArrayList<IEntity>(len);
            for (int i = 0; i < len; ++i) {
                Object f = Array.get(o, i);
                IEntity e = serialize(ctrl).fromObj(ctrl, f);
                entities.add(e);
            }
            return new ArrayEntity(entities);
        }
        return null;
    }
}
